﻿import * as types from './actionTypes'
import receiversReducer from './receiver/reducer'
import { sendSms } from '../svc/service-broker'
import { clearMsg } from './actions'

function setMsgContent(state, action) {
    return { ...state, msg: action.msg.replace('\\n', '\n') }
}

function setMsgType(state, { msgType }) {
    return { ...state, msgType }
}

function sendMsg(state, { dispatch }) {
    var { candidates, msg } = state;
    if (candidates && msg) {
        let receivers = candidates.map(c => ({ id: c.key, type: c.type }));
        sendSms(msg, receivers)
            .then(echo => {
                if (echo === 'success!') {
                    alert('消息发送成功!');
                } else {
                    alert(echo);
                }
            })
    }
    return state;
}

export default function send(state = {}, action) {
    switch (action.type) {
        case types.SET_MSG_CONTENT:
            return setMsgContent(state, action);
        case types.SET_MSG_TYPE:
            return setMsgType(state, action);
        case types.SEND_MSG:
            return sendMsg(state, action);
        default:
            return receiversReducer(state, action);
    }
}